package com.zzhua.test;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@Component
public class M3u8Component {
 	@Resource
    private FilePath filePath;

	public String mediaFileToJavaM3u8(MultipartFile file) throws Exception{
        if (file.isEmpty()) {
            throw new RuntimeException("未发现文件");
        }
        log.info("开始解析视频");
        long start = System.currentTimeMillis();
        //临时目录创建
        String path = new File(System.getProperty("user.dir")).getAbsolutePath();
        String tempFilePath = path+ filePath.getTempPath();
        if (!FileUtil.exist(tempFilePath)) {
            FileUtil.mkdir(tempFilePath);
        }
        String filePathName = tempFilePath + file.getOriginalFilename();
        File dest = new File(filePathName);
        try {
            file.transferTo(dest);
        }catch (Exception e){
            log.error("视频转m3u8格式存在异常，异常原因e:{}",e.getMessage());
        }

        //m3u8文件 存储路径
        String filePath = m3u8Util.generateFilePath(this.filePath.getBasePath());
        if (!FileUtil.exist(filePath)) {
            FileUtil.mkdir(filePath);
        }
        long end = System.currentTimeMillis();
        log.info("临时文件上传成功......耗时：{} ms", end - start);
        String m3u8FilePath = null;
        try {
            m3u8FilePath = FfmpegUtil.mp4ToM3u8(filePathName,filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("视频转换已完成 ！");
        return m3u8FilePath;
    }
}
